<template>
  <el-drawer modal-class="jzt-drawer" v-model="drawer" :before-close="handleClose">
    <template #header>
      <title-view :title="title + '发包信息'" />
    </template>
    <div class="edit-title-tips" v-if="title === '编辑' && ruleForm.approvalType === 2">
      <img style="width: 20px; height: 20px; margin-right: 8px; margin-top: 4px" src="@/assets/images/image/tips.png" alt="" />
      <div>当前发包信息存在编辑，内部审核后生效。已为您展示编辑后信息！</div>
    </div>
    <div class="drawer-body">
      <div class="name mb20">
        <span>{{ ruleForm.customerName }}</span
        ><span>丨</span><span>{{ ruleForm.address }}</span> <span>丨</span><span>{{ ruleForm.contractHourseArea || 0 }}㎡</span>
      </div>
      <el-form ref="ruleFormRef" :model="ruleForm" label-width="auto" class="demo-ruleForm" label-position="top">
        <el-form-item label="承包人" prop="userRoleName" required :rules="[{ required: true, message: '请选择承包人' }]">
          <el-select v-model="ruleForm.userRoleName" placeholder="请选择" @change="handleUser">
            <el-option
              :label="item.roleName + '-' + item.userName"
              :value="item.userId + '_' + item.roleId"
              v-for="item in contractorOption"
              :key="item.userId"
            />
          </el-select>
          <view style="font-size: 12px; color: #86909c">
            根据配置，承包人默认为“ <span style="color: #3d3d3d">{{ roleNames }}</span
            >”角色的负责人，如修改系统将自动更行对应角色负责人！
          </view>
        </el-form-item>
        <el-form-item label="客户合同" prop="contractId" required :rules="[{ required: true, message: '请选择客户合同' }]">
          <el-select v-model="ruleForm.contractId" placeholder="请选择" :disabled="title !== '添加'" @change="handleContract">
            <el-option :label="item.title" :value="item.contractId" v-for="item in contractOption" :key="item.contractId" />
          </el-select>
        </el-form-item>
        <el-form-item label="发包方式" prop="contracteesType" required :rules="[{ required: true, message: '请选择发包方式' }]">
          <div class="method">
            <div class="method-header">
              <el-radio-group v-model="ruleForm.contracteesType" :disabled="title !== '添加'" @change="ruleForm.factMoney = ''">
                <el-radio :value="1">按清单发包</el-radio>
                <el-radio :value="2">按面积发包</el-radio>
              </el-radio-group>
            </div>
            <div class="money" v-if="ruleForm.contracteesType === 2">
              <el-form-item
                label="发包金额"
                prop="factMoney"
                label-position="left"
                :rules="[{ required: true, message: '请输入发包金额' }]"
              >
                <el-input-number
                  controls-position="right"
                  v-model="ruleForm.factMoney"
                  placeholder="请输入"
                  style="width: 100%"
                  type="number"
                  min="1"
                  :controls="false"
                >
                  <template #suffix>
                    <span>元</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="辅料金额上限"
          prop="auxiliaryMoneyMax"
          required
          :rules="[{ required: true, message: '请输入辅料金额上限', trigger: 'blur' }]"
        >
          <el-input-number
            style="width: 100%"
            v-model="ruleForm.auxiliaryMoneyMax"
            placeholder=""
            type="number"
            disabled
            :precision="2"
            :controls="false"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="发包说明" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          label="编辑原因"
          prop="reason"
          required
          v-if="title === '编辑'"
          :rules="[{ required: true, message: '请输入编辑原因' }]"
        >
          <el-input
            v-model="ruleForm.reason"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <contract-upload
            :fileList="ruleForm.fileList || []"
            :accept="'.rar,.zip,.doc,.docx,.xlsx,.pdf,.jpg,.png'"
            multiple
            :max-size="100"
            :max-length="10"
            @upload-success="uploadImageList"
            @upload-remove="uploadImageListRemove"
            tips="支持上传rar/zip/doc/docx/xlsx/pdf/jpg/png，单个文件不超过100M"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose" color="#F2F3F5">取消</el-button>
      <el-button type="primary" @click="confirmClick">{{ confirm }}</el-button>
    </template>
  </el-drawer>
</template>
<script setup>
import { computed, ref } from "vue";
import {
  contractAdd,
  contractorDetails,
  contractSubmit,
  getContractList,
  getContractorList,
  getMoneyLimit
} from "@/apis/contracting";
import { ElMessage } from "element-plus";
import { setCache } from "@/utils/cache";

const emit = defineEmits(["handelSearch", "handleDetails"]);
const title = ref("添加");
const contractorOption = ref([]);
const contractOption = ref([]);
const ruleForm = ref({
  contracteesType: "",
  fileList: [],
  contractId: "",
  userRoleName: ""
});
const roleNames = computed(() => {
  let roleName = [];
  contractorOption.value.length > 0 &&
    contractorOption.value.map(item => {
      roleName.push(item.roleName);
    });
  if (title.value === "编辑") {
    roleName.push(ruleForm.value.roleName);
  }
  return Array.from(new Set(roleName)).toString();
});
const ruleFormRef = ref();
const drawer = ref(false);
const confirm = ref();
// 关闭
const handleClose = () => {
  ruleFormRef.value.resetFields();
  drawer.value = false;
};
// 提交
const confirmClick = () => {
  ruleFormRef.value.validate(async (valid, err) => {
    if (valid) {
      if (title.value === "添加") {
        // 点击添加弹窗明细项
        await contractAdd({
          ...ruleForm.value,
          contractHourseArea: ruleForm.value.contractHourseArea || 0
        });
        ElMessage.success("操作成功");
      } else {
        const stateToTypeMap = {
          2: "submit-apply", // 提交申请
          5: "reapply", // 重新申请
          default: "update" // 编辑
        };
        let type = stateToTypeMap[ruleForm.value.state] || stateToTypeMap.default;
        await contractSubmit(ruleForm.value, type);
        ElMessage.success("操作成功");
      }
      drawer.value = false;
      emit("handelSearch");
      if (title.value !== "编辑") {
        setCache("randomCode", Math.random().toString().slice(2, 8));
        emit("handleDetails", ruleForm.value);
      }
    }
  });
};
// 获取执行中合同列表
const getContract = async row => {
  const { data } = await getContractList({ customerId: row.customerId });
  contractOption.value = data;
};
// 获取承包人
const getContractor = async row => {
  const { data } = await getContractorList(row.customerId, 6);
  if (title.value === "添加") {
    let userRole = data.find(item => item.chargePerson);
    if (userRole) {
      ruleForm.value.userRoleName = userRole.userId + "_" + userRole.roleId;
      ruleForm.value.jobUserName = userRole.userName;
      ruleForm.value.roleName = userRole.roleName;
      ruleForm.value.roleId = userRole.roleId;
      ruleForm.value.jobUserId = userRole.userId;
    }
  }
  contractorOption.value = data;
};
const handleUser = id => {
  let objRole = contractorOption.value.find(item => item.userRoleId === id);
  ruleForm.value.jobUserName = objRole.userName;
  ruleForm.value.roleName = objRole.roleName;
  ruleForm.value.roleId = objRole.roleId;
  ruleForm.value.jobUserId = objRole.userId;
  ruleForm.value.userRoleName = objRole.roleName + "-" + objRole.userName;
};
const handleContract = async id => {
  let objContract = contractOption.value.find(item => item.contractId === id);
  ruleForm.value.contractTitle = objContract.title;
  const { data } = await getMoneyLimit(id);
  ruleForm.value.auxiliaryMoneyMax = data || 0;
};
// 新增发包
const openAdd = async row => {
  title.value = "添加";
  confirm.value = "去确认发包项";
  drawer.value = true;
  await getContract(row);
  ruleForm.value = {
    ...ruleForm.value,
    ...row,
    fileList: [],
    userRoleName: ""
  };
  ruleFormRef.value?.resetFields();
  await getContractor(row);
};
// 编辑
const openEdit = async (row, butText, text) => {
  title.value = text;
  confirm.value = butText;
  getContract(row);
  getContractor(row);
  const { data } = await contractorDetails(row.contracteesId);
  ruleForm.value = data;
  ruleForm.value.userRoleName = data.roleName + "_" + data.jobUserName;
  drawer.value = true;
  if (text === "编辑") {
    ruleForm.value.reason = "";
  }
};

const uploadImageList = data => {
  (ruleForm.value.fileList ??= []).push({
    ...data
  });
};
// 删除上传
const uploadImageListRemove = index => {
  ruleForm.value.fileList.splice(index, 1);
};
defineExpose({ openAdd, openEdit });
</script>
<style scoped lang="scss">
.mb20 {
  margin-bottom: 20px;
}

.name {
  padding-bottom: 9px;
  border-bottom: 1px solid #dcdfe6;

  :nth-of-type(1) {
    color: #3d3d3d;
  }

  :nth-of-type(2) {
    color: #e1e6ed;
  }

  :nth-of-type(3) {
    color: #86909c;
  }

  :nth-of-type(4) {
    color: #e1e6ed;
  }

  :nth-of-type(5) {
    color: #86909c;
  }
}

:deep(.el-select__wrapper),
:deep(.el-input__wrapper),
:deep(.el-input-group__append),
:deep(.el-input__count),
:deep(.el-textarea__inner) {
  background-color: #f2f3f5 !important;
  box-shadow: none !important;
}

:deep(.upload-picture-card) {
  border: none !important;
}

.method {
  width: 100%;
  background: #ffffff;
  border: 1px solid #f0f0f0;

  &-header {
    height: 40px;
    padding: 9px 20px;
    background: #f5f7fa;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #f0f0f0;

    :deep(.el-radio-group) {
      width: 100% !important;
    }
  }
}

.money {
  padding: 10px 15px;

  :deep(.el-form-item__label) {
    margin-bottom: 0 !important;
    line-height: inherit !important;
  }
}

.edit-title-tips {
  background: #ffd9c2;
  display: flex;
  font-size: 12px;
  color: #000000;
  line-height: 22px;
  padding: 8px 24px;
}

.drawer-body {
  padding: 20px !important;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background: #ffffff !important;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #f2f3f5;
}
</style>
